<?php

/**
 * alltosun.com  openapi_helper.php
 * ============================================================================
 * 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 石武浩 (shiwh@alltosun.com) $
 * $Date:  2014-6-19 下午4:51:31 $
 * $Id$
*/

class openapi_helper
{
    /**
     * 通过订单获取支付宝的支付帐号
     * @param int $order_id
     * @return array
     */
    public static function get_order_pay_account($order_id)
    {
        $order_id = (int)$order_id;
        if(!$order_id) {
            return array();
        }
        $order_info = _uri('order', $order_id);
        if(!$order_info) {
            return array();
        }
        $pay_account = $order_info['pay_account'];

        // 支付宝
        if($order_info['pay_type'] == 1) {
            $account_list = Config::get('alipay_account_list');
            // 部分字段
            return array(
                            'partner'      => $account_list[$pay_account]['partner'],
                            'key'   => $account_list[$pay_account]['alipay_key'],
                            'seller_email' => $account_list[$pay_account]['seller_email'],
            );
        } else {
            // @todo 其他支付方式
            return array();
        }
    }

    /**新浪微博connet更新
     * @param unknown $connect_id
     * @param unknown $data
     */
    public static function update_connect($connect_id, $data = array())
    {
        _model('connect')->update($connect_id, $data);
    }

    /**QQconnet更新
     * @param unknown $connect_id
     * @param unknown $data
     */
    public static function update_connect_qq($connect_id, $data = array())
    {
        _model('connect_qq')->update($connect_id, $data);
    }

    /**
     * 添加用户的同步关联
     * @param int $user_id
     */
    public static function add_user_connect($user_id, $res_name)
    {
        $old_filter = array(
            'user_id'  => $user_id,
            'res_name' => $res_name
        );
        $old_info = _uri('user_connect', $old_filter);
        if (!$old_info) {
            _model('user_connect')->create($old_filter);
        }

        return true;
    }

    /**
     * 删除用户的同步关联
     * @param int $user_id
     */
    public static function del_user_connect($user_id, $res_name)
    {
        $old_filter = array(
            'user_id'  => $user_id,
            'res_name' => $res_name
        );

        return !!_model('user_connect')->delete($old_filter);
    }

    /**
     * 取用户绑定且需同步的资源
     * @return array
     */
    public static function get_user_connect_res($user_id)
    {
        $filter = array('user_id'=>$user_id);
        $connect_list = _model('user_connect')->getFields('res_name', $filter);

        return $connect_list;
    }

    /**
     * 取用户绑定且需同步的资源
     * @return array
     */
    public static function get_user_connect($user_id)
    {
        $filter = array('user_id'=>$user_id);
        $connect_list = _model('user_connect')->getList($filter);

        return $connect_list;
    }

    /**
     * 发布微博
     * @param string $content
     * @param string $pic_path
     * @param array $connect_list
     * @return string
     */
    public static function sync_connect($content, $pic_path = '', $connect_list = array())
    {
        $error_info = '';
        if (!$connect_list) {
            $user_id = user_helper::get_user_id();
            $connect_list = self::get_user_connect($user_id);
        }

        if (!$connect_list) {
            return false;
        }

        //@todo
        //$connect_list = array(
            //array('res_name'=>'sinaweibo')
        //);

        foreach ($connect_list as $k=>$v) {
            // 是否同步成功
            $success = 0;
            try {
                $res_name = $v['res_name'];

                if (in_array($res_name, array('sinaweibo', 'qqweibo'))) {
                    $check_info = AnOpenApi($res_name)->authorize();
                    if (!$check_info || $check_info['status'] != 'ok') {
                        $error_info .= $res_name.'授权验证失败,需重新授权';
                        continue;
                    }

                    $info = AnOpenApi($res_name)->update($content, $pic_path);
                    if (!empty($info['error_code'])) {
                        $error_info .= $res_name.'开放平台信息同步错误';
                    } else {
                        $success = 1;
                    }
                }

            } catch (Exception $e) {
                if (ONDEV) {
                    exit(var_dump($e));
                }
            }
        }

        return $error_info;
    }

    /**
     * 微博/QQ动态头像本地化
     */
    public static function remote_img_to_local($file, $ext = 'jpg')
    {
        $time = time();
        $folder = UPLOAD_PATH.date('/Y/m/d', $time);

        if (!file_exists($folder) && !@mkdir($folder, 0777, true)) {
            return '';
        }

        // u为microseconds，> PHP 5.2.2
        if (version_compare(PHP_VERSION, '5.2.2') >= 0) {
            $current_time = date('YmdHisu', $time);
        } else {
            $current_time = date('YmdHis', $time);
        }

        $random = mt_rand(0, 100);
        $target = $folder.'/'.$current_time.'_'.$random.'.'.$ext;
        $target = trim($target, '.');

        $content = file_get_contents($file);
        $res = file_put_contents($target, $content);
        if ($res) {
           $file_path = substr($target, strlen(UPLOAD_PATH));
           // 生成缩略图
           make_thumb($file_path, 'user');

           return $file_path;
        } else {
           return '';
        }
    }

    /**
     * 获取用户是否已经绑定了账号
     * @return array();
     */
    public static function get_user_bind_list($site_id = '', $user_id = '')
    {
        if ($user_id == '') {
            $user_id = user_helper::get_user_id();
        }

        if ($site_id == 5) {
            $connect_list = _model('connect_qq')->getList(array('user_id'=>$user_id));
        } else {
            $connect_list = _model('connect')->getList(array('user_id'=>$user_id));
        }

        return $connect_list;
    }

    /**
     * *********************************************************************************************** *
     * 以下所有方法为支付相关
     */

    /**
     * 除去待签名参数数组中的空值和签名参数
     */
    public static function param_filter($param, $no_space = 0)
    {
        if (empty($param)) {
            return array();
        }

        $para_filter = array();
        foreach ($param as $k=>$v) {
            if ($k == "sign" || $k == "sign_type" || $k == "anu" || $k == 'bank' || $k == 'signature' || $k == 'signMethod' || $k == 'key') {
                continue;
            }
            if ($no_space == 0 && ('' == $v || null == $v || 'null' == $v)) {
                continue;
            }
            $para_filter[$k] = $v;
        }

        return $para_filter;
    }

    /**
     * 对数组排序
     * @param $param 排序前的数组
     * return 排序后的数组
     */
    public static function param_sort($param) {
        ksort($param);
        reset($param);
        return $param;
    }

    /**
     * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param $param 需要拼接的数组
     * @param $is_urlencode 是否unlencode格式化
     * return 拼接完成以后的字符串
     */
    function create_link_string($param, $is_urlencode = 0) {
        $arg  = "";
        foreach ($param as $k=>$v) {
            if ($is_urlencode == 1) {
                $arg .= $k."=".urlencode($v)."&";
            } else {
                $arg .= $k."=".$v."&";
            }
        }

        //去掉最后一个&字符
        $arg = rtrim(trim($arg), '&');

        //如果存在转义字符，那么去掉转义
        if(get_magic_quotes_gpc()) $arg = stripslashes($arg);

        return $arg;
    }

    /**
     * 签名字符串
     * @param $prestr 需要签名的字符串
     * @param $key 私钥
     * @param $pay_type 支付方式
     * return 签名结果
     */
    public static function md5_sign($prestr, $key, $pay_type) {
        $sing_string = '';
        switch ($pay_type) {
            case "alipay" :  // 支付宝签名方式
                $sing_string = md5($prestr . $key);
                break;
            case "quickpay" :
                $prestr .= '&';
                $sing_string = md5($prestr . md5($key));
                break;
            case "tenpay" :
                $sing_string = strtoupper(md5($prestr . "&key=" . $key));
                break;
            default :
                $sing_string = "";
        }

        return $sing_string;
    }

    /**
     * 验证签名
     * @param $prestr 需要签名的字符串
     * @param $sign 签名结果
     * @param $key 私钥
     * return 签名结果
     */
    public static function md5_verify($prestr, $sign, $key, $pay_type = 'alipay') {
        $mysgin = self::md5_sign($prestr, $key, $pay_type);

        if($mysgin == $sign) {
            return true;
        }
        else {
            return false;
        }
    }

    /**
     * 生成签名结果
     * @param $param 已排序要签名的数组
     * return 签名结果字符串
     */
    public static function build_request_sign($param, $key, $pay_type, $sing_type = 'MD5') {
        //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        $prestr = self::create_link_string($param);

        $mysign = "";
        switch ($pay_type) {
            case "alipay" :  // 支付宝签名方式
            case 'quickpay' :
            case 'tenpay' :
                if ($sing_type == 'MD5') {
                    $mysign = self::md5_sign($prestr, $key, $pay_type);
                }
                break;

            default :
                $mysign = "";
        }

        return $mysign;
    }
}